<!--
 * @Descripttion: 编辑满减返佣
 * @Author: xiao li
 * @Date: 2020-07-06 12:17:07
 * @LastEditors: xiao li
 * @LastEditTime: 2021-11-23 15:45:09
-->
<template>
  <div class="lb-edit-card">
    <top-nav :title="navTitle" :isBack="true"></top-nav>
    <div class="page-main">
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="aForm"
        label-width="140px"
        class="basic-form"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="subForm.title"
            maxlength="40"
            show-word-limit
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="参与必授权">
          <el-checkbox-group v-model="checkList">
            <div
              v-for="(item, index) in authList"
              :key="index"
              :style="{
                display: 'inline-block',
                marginLeft: index === 0 ? 0 : '15px'
              }"
            >
              <el-checkbox :label="item.title"></el-checkbox>
              <lb-tool-tips v-if="item.tips">{{ item.tips }}</lb-tool-tips>
            </div>
            <lb-tool-tips>选中后，需用户授权手机号才能领取此福利</lb-tool-tips>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="优惠金额" prop="reduction">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.reduction"
            :controls="false"
            :precision="2"
            :min="0.01"
            placeholder="请输入优惠金额,最低0.01元"
          ></el-input-number>
          元
        </el-form-item>
        <el-form-item label="最低消费" prop="full">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.full"
            :controls="false"
            :precision="2"
            :min="0.02"
            placeholder="请输入最低消费金额,最低0.02元"
          ></el-input-number>
          元
          <lb-tool-tips
            >付款金额不小于此处填写的金额才可以使用满减券</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="可用人员" prop="use_condition">
          <el-radio-group v-model="subForm.use_condition">
            <el-radio :label="0">不限</el-radio>
            <el-radio :label="1">指定公司/部门</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="companyFormRules"
        ref="bForm"
        label-width="140px"
        class="basic-form"
        v-if="subForm.use_condition === 1"
      >
        <el-form-item label="" prop="company">
          <el-cascader
            v-model="subForm.company"
            collapse-tags
            :options="base_company"
            @change="choiceAllCompanyItem"
            :props="{
              multiple: true,
              checkStrictly: true,
              label: 'name',
              value: 'id'
            }"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>

      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="cForm"
        label-width="140px"
        class="basic-form"
      >
        <el-form-item label="总发放量" prop="num">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.num"
            :controls="false"
            :precision="0"
            :min="1"
            placeholder="请输入总发放量"
          ></el-input-number>
          张
        </el-form-item>

        <el-form-item label="使用有效期" prop="over_time">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.over_time"
            :controls="false"
            :precision="0"
            :min="1"
            placeholder="请输入使用有效期"
          ></el-input-number>
          天
          <lb-tool-tips
            >以用户领取时间开始计算，超过此处填写的天数，未用满减券就会过期</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="员工返佣" prop="cash">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.cash"
            :controls="false"
            :precision="2"
            :min="0"
            placeholder="请输入员工返佣金额"
          ></el-input-number>
          元
        </el-form-item>

        <el-form-item>
          <lb-button @click="submitFormInfo" type="primary">{{
            $t('action.save')
          }}</lb-button>
          <lb-button @click="goBack">{{ $t('action.back') }}</lb-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      navTitle: '',
      base_company: [],
      companyResult: [],
      checkList: [],
      options: [],
      value: [],
      loading: false,
      authList: [
        {
          title: '手机号',
          key: 'is_phone'
        }
      ],
      form: {
        copyCompanyId: []
      },
      companyFormRules: {
        company: { required: true, type: 'array', message: '请选择当前公司', trigger: 'change' }
      },
      // 基本信息
      subForm: {
        title: '',
        is_phone: 0,
        reduction: null,
        full: null,
        over_time: null,
        // use_condition 指定可用 => 0不限制；1公司/部门
        use_condition: 1,
        num: 0,
        // selling_type 返佣记录类型 => 0金额：cash；1比例：balance
        selling_type: 0,
        cash: null
      },
      subFormRules: {
        title: { required: true, type: 'string', message: '请输入标题', trigger: 'blur' },
        use_condition: { required: true, type: 'number', message: '请选择指定可用', trigger: 'blur' },
        selling_type: { required: true, type: 'number', message: '请选择返佣类型', trigger: 'blur' },
        reduction: { required: true, type: 'number', message: '请输入优惠金额', trigger: 'blur' },
        full: { required: true, type: 'number', message: '请输入最低消费金额', trigger: 'blur' },
        over_time: { required: true, type: 'number', message: '请输入使用有效期', trigger: 'blur' },
        num: { required: true, type: 'number', message: '请输入满减券发放总数量', trigger: 'blur' }
      }
    }
  },
  async created () {
    let { id } = this.$route.query
    if (id) {
      this.id = id
      await this.getDetail(id)
    }
    this.navTitle = this.$t(id ? 'menu.ReductionEdit' : 'menu.ReductionAdd')
    await this.getBaseCompany()
    await this.getBaseStaffInfo()
  },
  methods: {
    remoteMethod (query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.getBaseStaffInfo(query)
        }, 200)
      } else {
        this.options = []
      }
    },
    async getBaseStaffInfo (name) {
      let { data } = await this.$api.getBaseStaffInfo({
        name
      })
      this.options = data
    },
    async getBaseCompany () {
      // 基本信息验证
      let { data: company } = await this.$api.getBaseCompany()
      this.handleCompanyOptions(company)
      this.base_company = company
    },
    async getDetail (id) {
      let { code, data } = await this.$api.reductionActiveInfo({ id })
      if (code !== 200) return
      let copyCompany = JSON.parse(JSON.stringify(data.company))
      let resCompany = copyCompany.length === this.companyResult.length ? [
        [0], ...copyCompany
      ] : copyCompany
      data.company = resCompany
      this.subForm = data
      let checkItem = []
      this.authList.map(item => {
        if (data[item.key] === 1) {
          checkItem.push(item.title)
        }
      })
      this.checkList = checkItem
      this.form.copyCompanyId = resCompany
    },
    handleCompanyOptions (data, arr = []) {
      for (let i = 0, len = data.length; i < len; i++) {
        let newArr = JSON.parse(JSON.stringify(arr))
        newArr.push(data[i].id)
        this.companyResult.push(JSON.parse(JSON.stringify(newArr)))
        if (data[i].children && data[i].children.length) {
          this.handleCompanyOptions(data[i].children, newArr)
        }
      }
    },
    /**
     * @method 全选公司
     */
    choiceAllCompanyItem (val) {
      let { companyResult } = this
      // true = 添加  false 取消、减少
      let rType = val.length > this.form.copyCompanyId.length
      let firstVal = val[0] && val[0][0]
      if (rType) {
        // 添加
        if (firstVal && val.length === companyResult.length) {
          // 其他都选完了，就只有全选没选了
          this.subForm.company = [[0], ...val]
        } else if (firstVal === 0) {
          this.subForm.company = [[0], ...companyResult]
        }
      } else {
        // 减少
        if (firstVal === 0) {
          // 第一个为0 只取消全选
          let copyArr = JSON.parse(JSON.stringify(val))
          copyArr.splice(0, 1)
          this.subForm.company = copyArr
        } else if (val.length === companyResult.length) {
          // 清空
          this.subForm.company = []
        } else {
          this.subForm.company = val
        }
      }
      this.form.copyCompanyId = this.subForm.company
    },
    getCover (imgs) {
      this.subForm.cover = imgs
    },
    getImgs (imgs) {
      this.subForm.imgs = imgs
    },
    getShareImg (imgs) {
      this.subForm.share_img = imgs
    },
    handleMomentTime (time) {
      return new Date(time * 1000)
    },
    handleTimes (time) {
      return parseInt(new Date(time).getTime() / 1000)
    },
    goBack () {
      this.$router.back(-1)
    },
    async submitFormInfo () {
      let subForm = JSON.parse(JSON.stringify(this.subForm))
      console.log(subForm)
      let formArr = ['aForm', 'cForm']
      if (subForm.use_condition === 1) {
        formArr.push('bForm')
      }
      let flag = true
      for (let i = 0, len = formArr.length; i < len; i++) {
        this.$refs[formArr[i]].validate(valid => {
          if (!valid) {
            flag = false
            return false
          }
        })
      }
      if (flag) {
        this.authList.map(item => {
          subForm[item.key] = 0
          this.checkList.map(aitem => {
            if (item.title === aitem) {
              subForm[item.key] = 1
            }
          })
        })
        if (subForm.use_condition === 1 && subForm.company[0][0] === 0) {
          subForm.company.splice(0, 1)
        }

        let methodModel = subForm.id ? 'reductionActiveUpdate' : 'reductionActiveAdd'
        let { code } = await this.$api[methodModel](subForm)
        if (code !== 200) return
        this.$message.success(this.$t('tips.successSub'))
        this.goBack()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-edit-card {
  width: 100%;
  .el-input,
  .el-select,
  .lb-input-number,
  .el-cascader {
    width: 400px;
  }
}
</style>
